import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:csv/csv.dart';
import '../utils/encoding_util.dart';

/// 测试CSV文件编码问题
class TestEncodingCsv extends StatefulWidget {
  const TestEncodingCsv({Key? key}) : super(key: key);

  @override
  State<TestEncodingCsv> createState() => _TestEncodingCsvState();
}

class _TestEncodingCsvState extends State<TestEncodingCsv> {
  String _result = '点击按钮测试CSV文件编码';
  bool _isLoading = false;
  TextEditingController _pathController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _pathController.text = 'test_words_final.csv'; // 默认测试文件路径
  }

  @override
  void dispose() {
    _pathController.dispose();
    super.dispose();
  }

  Future<void> _testEncoding() async {
    final filePath = _pathController.text.trim();
    if (filePath.isEmpty) {
      setState(() {
        _result = '请输入CSV文件路径';
      });
      return;
    }

    setState(() {
      _isLoading = true;
      _result = '正在测试文件编码...';
    });

    try {
      final file = File(filePath);
      if (!await file.exists()) {
        setState(() {
          _isLoading = false;
          _result = '文件不存在: $filePath';
        });
        return;
      }

      // 读取文件字节
      final Uint8List bytes = await file.readAsBytes();
      
      // 检查BOM标记
      final bool hasBom = bytes.length >= 3 && 
          bytes[0] == 0xEF && 
          bytes[1] == 0xBB && 
          bytes[2] == 0xBF;
      
      // 去除BOM标记
      final Uint8List processedBytes = EncodingUtil.removeBomFromBytes(bytes);
      
      // 尝试不同编码方式解码
      String utf8Content = '';
      String latin1Content = '';
      String charCodesContent = '';
      List<List<dynamic>> utf8CsvTable = [];
      List<List<dynamic>> latin1CsvTable = [];
      List<List<dynamic>> charCodesCsvTable = [];
      
      try {
        utf8Content = EncodingUtil.decodeBytes(processedBytes);
        utf8CsvTable = const CsvToListConverter().convert(utf8Content);
      } catch (e) {
        utf8Content = '解码失败: $e';
      }
      
      try {
        latin1Content = String.fromCharCodes(processedBytes, 0, processedBytes.length);
        latin1CsvTable = const CsvToListConverter().convert(latin1Content);
      } catch (e) {
        latin1Content = '解码失败: $e';
      }
      
      try {
        charCodesContent = String.fromCharCodes(processedBytes);
        charCodesCsvTable = const CsvToListConverter().convert(charCodesContent);
      } catch (e) {
        charCodesContent = '解码失败: $e';
      }

      setState(() {
        _isLoading = false;
        _result = '文件: $filePath\n';
        _result += '文件大小: ${bytes.length} 字节\n';
        _result += '包含BOM标记: ${hasBom ? "是" : "否"}\n\n';
        
        _result += '=== UTF-8解码 ===\n';
        if (utf8CsvTable.isNotEmpty) {
          _result += '解析成功，共 ${utf8CsvTable.length} 行\n';
          _result += '表头: ${utf8CsvTable[0].join(", ")}\n';
          if (utf8CsvTable.length > 1) {
            _result += '第一行数据: ${utf8CsvTable[1].join(", ")}\n';
          }
        } else {
          _result += utf8Content + '\n';
        }
        
        _result += '\n=== Latin1解码 ===\n';
        if (latin1CsvTable.isNotEmpty) {
          _result += '解析成功，共 ${latin1CsvTable.length} 行\n';
          _result += '表头: ${latin1CsvTable[0].join(", ")}\n';
          if (latin1CsvTable.length > 1) {
            _result += '第一行数据: ${latin1CsvTable[1].join(", ")}\n';
          }
        } else {
          _result += latin1Content + '\n';
        }
        
        _result += '\n=== CharCodes解码 ===\n';
        if (charCodesCsvTable.isNotEmpty) {
          _result += '解析成功，共 ${charCodesCsvTable.length} 行\n';
          _result += '表头: ${charCodesCsvTable[0].join(", ")}\n';
          if (charCodesCsvTable.length > 1) {
            _result += '第一行数据: ${charCodesCsvTable[1].join(", ")}\n';
          }
        } else {
          _result += charCodesContent + '\n';
        }
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _result = '测试出错：$e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('CSV编码测试')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
              controller: _pathController,
              decoration: const InputDecoration(
                labelText: 'CSV文件路径',
                hintText: '输入CSV文件的完整路径',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _isLoading ? null : _testEncoding,
              child: const Text('测试文件编码'),
            ),
            const SizedBox(height: 20),
            Expanded(
              child: _isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : SingleChildScrollView(
                      child: Text(
                        _result,
                        style: const TextStyle(fontSize: 14),
                      ),
                    ),
            ),
          ],
        ),
      ),
    );
  }
}